package com.itheima.web.servlet;

import com.itheima.domain.Address;
import com.itheima.domain.User;
import com.itheima.factory.BeanFactory;
import com.itheima.service.AddressService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/AddressServlet")
@MultipartConfig
public class AddressServlet extends BaseServlet {

    AddressService addressService= (AddressService) BeanFactory.getBean("addressService");
    //模板
    protected void xxx(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
//根据uid查询地址列表
    protected void findByUid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.校验session中是否有User
        User currentUser = (User) request.getSession().getAttribute("currentUser");
       if (currentUser==null){
           response.sendRedirect(request.getContextPath()+"/index.jsp");
           return;
       }
        //2.如果有user 根据uid查询service返回地址列表
       List<Address>addressList= addressService.findByUid(currentUser.getUid());
        //3.将list设置到request域中
        request.setAttribute("addressList",addressList);
        //4.转发到home_address.jsp
        request.getRequestDispatcher("/home_address.jsp").forward(request,response);
    }
    protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //校验session中是否有User
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (currentUser==null){
            response.sendRedirect(request.getContextPath()+"/index.jsp");
            return;
        }
        try {
            //1.接受请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        //2.封装到address实体
        Address param=new Address();
            BeanUtils.populate(param,parameterMap);
            // 指定非默认地址
            param.setIsdefault("0");
            // 保存用户
            param.setUser(currentUser);

            //3.调用service保存
            addressService.save(param);
            //4.重定向
            response.sendRedirect(request.getContextPath()+"/AddressServlet?action=findByUid");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}